import { h } from 'vue'
import {
  FundProjectionScreenOutlined,
  ControlOutlined,
  IdcardOutlined,
  DatabaseOutlined,
  BranchesOutlined,
  GoldOutlined,
  TransactionOutlined,
  RedEnvelopeOutlined,
  UserOutlined,
} from '@ant-design/icons-vue'
import { useAuthUserStore } from '@/store/authUserStore'

// 定義 MenuItem 類型
interface MenuRouterItem {
  name: string //唯一標識
  label: string //菜單名稱
  path?: string //路由路徑
  icon?: any // 圖標
  component?: () => Promise<any> // 返回 Promise 的函數，用於動態加載組件
  children?: MenuRouterItem[] // 子項目
}
const menuRouteItems: MenuRouterItem[] = [
  {
    name: 'Dashboard',
    label: '儀表盤',
    path: '/dashboard',
    icon: () => h(FundProjectionScreenOutlined),
    component: () => import('@/pages/DashboardPage.vue'),
  },

  {
    name: 'BasicData',
    label: '基礎數據',
    icon: () => h(DatabaseOutlined),
    children: [
      {
        name: 'Doctor',
        label: '醫師管理',
        path: '/doctor',
        component: () => import('@/pages/doctor/DoctorPage.vue'),
      },
      {
        name: 'Product',
        label: '產品管理',
        path: '/product',
        component: () => import('@/pages/product/ProductPage.vue'),
      },
    ],
  },
  {
    name: 'ConsultRule',
    label: '診金規則',
    icon: () => h(BranchesOutlined),
    children: [
      {
        name: 'Promotion',
        label: '推廣活動',
        path: '/promotion',
        component: () => import('@/pages/consult_rule/PromotionPage.vue'),
      },
      {
        name: 'ConsultPlan',
        label: '診金分成方案',
        path: '/consult-plan',
        component: () => import('@/pages/consult_rule/ConsultPlanPage.vue'),
      },
      {
        name: 'CustomConsultType',
        label: '自定義診金類型',
        path: '/custom-consult-type',
        component: () => import('@/pages/consult_rule/CustomConsultTypePage.vue'),
      },
      {
        name: 'ReductionPlan',
        label: '減免方案',
        path: '/reduction-plan',
        component: () => import('@/pages/consult_rule/ReductionPlanPage.vue'),
      },
      {
        name: 'SpecifyService',
        label: '指定服務',
        path: '/specify-service',
        component: () => import('@/pages/consult_rule/SpecifyServicePage.vue'),
      },
    ],
  },
  // {
  //   name: 'Product',
  //   label: '產品管理',
  //   icon: () => h(DatabaseOutlined),
  //   children: [
  //     {
  //       name: 'ProductList',
  //       label: '產品列表',
  //       path: '/product',
  //       component: () => import('@/pages/product/ProductPage.vue'),
  //     },
  //     // {
  //     //   name: 'Category',
  //     //   label: '業務大類',
  //     //   path: '/category',
  //     //   component: () => import('@/pages/product/CategoryPage.vue'),
  //     // },
  //   ],
  // },
  {
    name: 'ShareRule',
    label: '分成規則',
    icon: () => h(GoldOutlined),
    children: [
      {
        name: 'Additional',
        label: '附加項目分成',
        path: '/share-rule/additional',
        component: () => import('@/pages/share_rule/AdditionalSharePage.vue'),
      },
      {
        name: 'Regular',
        label: '常規銷售分成',
        path: '/share-rule/regular',
        component: () => import('@/pages/share_rule/RegularSharePage.vue'),
      },
      {
        name: 'Extra',
        label: '附加推廣分成',
        path: '/share-rule/extra',
        component: () => import('@/pages/share_rule/ExtraSharePage.vue'),
      },
    ],
  },
  {
    name: 'SalesCommission',
    label: '銷售&佣金',
    icon: () => h(TransactionOutlined),
    children: [
      {
        name: 'Invoice',
        label: '醫單列表',
        path: '/sales/invoice',
        component: () => import('@/pages/sale/InvoicePage.vue'),
      },
      {
        name: 'MonthlyStat',
        label: '月度統計',
        path: '/sales/monthly-stat',
        component: () => import('@/pages/sale/MonthlyStatPage.vue'),
      },
      {
        name: 'CommissionList',
        label: '佣金列表',
        path: '/commission',
        component: () => import('@/pages/commission/CommissionPage.vue'),
      },
      {
        name: 'ShopStatMonthly',
        label: '店舖月統計',
        path: '/sales/shop-stat-monthly',
        component: () => import('@/pages/commission/ShopStatMonthlyPage.vue'),
      },
    ],
  },
  {
    name: 'Bonus',
    label: '獎金相關',
    icon: () => h(RedEnvelopeOutlined),
    children: [
      {
        name: 'BonusList',
        label: '獎金列表',
        path: '/bonus',
        component: () => import('@/pages/bonus/BonusPage.vue'),
      },
      {
        name: 'BonusSetting',
        label: '獎金設置',
        path: '/bonus/setting',
        component: () => import('@/pages/bonus/BonusSettingPage.vue'),
      },
    ],
  },
    {
    name: 'System',
    label: '系統管理',
    icon: () => h(ControlOutlined),
    children: [
      {
        name: 'User',
        label: '用戶列表',
        path: '/user',
        component: () => import('@/pages/user/UserPage.vue'),
      },
      {
        name: 'Role',
        label: '角色列表',
        path: '/role',
        component: () => import('@/pages/role/RolePage.vue'),
      },
      {
        name: 'SystemMessage',
        label: '系統消息',
        path: '/system-message',
        component: () => import('@/pages/system/SystemMessagePage.vue'),
      },
      {
        name: 'SystemSetting',
        label: '系統設置',
        path: '/system-setting',
        component: () => import('@/pages/system/SystemSettingPage.vue'),
      },
      {
        name: 'OperationLog',
        label: '操作記錄',
        path: '/operation-log',
        component: () => import('@/pages/system/OperationLogPage.vue'),
      },
    ],
  },
  {
    name: 'Personal',
    label: '個人中心',
    icon: () => h(UserOutlined),
    children: [
      {
        name: 'Profile',
        label: '我的主頁',
        path: '/profile',
        component: () => import('@/pages/personal/ProfilePage.vue'),
      },
      {
        name: 'Setting',
        label: '賬戶設置',
        path: '/setting',
        component: () => import('@/pages/personal/SettingPage.vue'),
      },
    ],
  },

]

// 根據用戶得到的菜單name集合篩選，動態生成菜單
// 遞歸過濾菜單項目，根據用戶擁有的菜單名稱進行篩選
function hasAccess(item: MenuRouterItem, userMenusSet: Set<string>) {
  return userMenusSet.has(item.name) || (item.children && item.children.some((child) => userMenusSet.has(child.name)))
}

function filterMenuItems(menuItems: MenuRouterItem[], userMenus: string[]): MenuRouterItem[] {
  const userMenusSet = new Set(userMenus)
  return menuItems
    .filter((item) => hasAccess(item, userMenusSet))
    .map((item) => {
      if (item.children) {
        const filteredChildren = filterMenuItems(item.children, userMenus)
        return { ...item, children: filteredChildren.length > 0 ? filteredChildren : undefined }
      }
      return item
    })
}

// 處理用戶菜單，根據用戶擁有的菜單名稱篩選出可用菜單，並生成 Ant Design 菜單數據
function processUserMenus() {
  // 獲取用戶菜單權限存儲
  const authUserStore = useAuthUserStore()
  const { userMenus } = authUserStore
  // 過濾出用戶有權限訪問的菜單
  const filteredMenus = filterMenuItems(menuRouteItems, userMenus)
  // console.log('userMenusRouterItmes', filteredMenus)
  // 生成 Ant Design 菜單數據
  const userMenuItmes = generateAntDesignMenu(filteredMenus)
  return { userMenuItmes }
}

// 定義 AntDesignMenuItem 類型
interface AntDesignMenuItem {
  key: string
  label: string
  icon?: any
  title?: string
  children?: AntDesignMenuItem[]
}
/**
 * 生成 Ant Design 菜單所需的數據
 * @param menuConfig - 菜單配置項數組
 * @returns Ant Design 菜單數據數組
 */
function generateAntDesignMenu(menuConfig: MenuRouterItem[]): AntDesignMenuItem[] {
  return menuConfig.map(({ name, label, icon, children }) => ({
    key: name,
    label,
    icon: icon || null,
    children: children ? generateAntDesignMenu(children) : null,
  })) as AntDesignMenuItem[]
}

export { menuRouteItems, processUserMenus, generateAntDesignMenu }
